#include "ChatListView.h"

ChatListView::ChatListView(QWidget *parent):QListView(parent) {}

void ChatListView::contextMenuEvent(QContextMenuEvent *event)
{
    // 获取当前的索引
    QModelIndex index = indexAt(event->pos());
    if(!index.isValid()){
        return;
    }

    // 创建上下文菜单
    QMenu menu(this);
    // 设置菜单样式表
    menu.setStyleSheet(
        "QMenu {"
        "   background-color: rgb(240, 240, 240);"
        "   border-radius: 3px;"
        "   border: 0.5px solid rgb(0, 0, 0);"
        "}"
        "QMenu::item {"
        "   padding: 10px;"
        "   text-align: left;"
        "}"
        "QMenu::item:selected {"
        "   background-color: rgb(200, 200, 200);"
        "}"
        "QMenu::item:pressed {"
        "   background-color: rgb(180, 180, 180);"
        "}");
    // 添加菜单项
    QAction* action1 = menu.addAction("移除会话");

    // 执行菜单并获取用户选择
    QAction* selectedAction = menu.exec(event->globalPos());
    if(selectedAction == action1){
        emit menuChoice(index);
    }
}

ChatItemDelegate::ChatItemDelegate(QWidget *parent):QStyledItemDelegate(parent){}

QSize ChatItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);
    return QSize(190,50);// 设置大小为190×50
}

void ChatItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    // 1.检查是否有效
    if (!index.isValid()){
        return;
    }
    painter->save();// 保存当前绘制状态
    painter->setRenderHint(QPainter::Antialiasing); // 反锯齿
    painter->setRenderHint(QPainter::TextAntialiasing); // 文本反锯齿

    // 2.绘制每一项的背景颜色（鼠标悬停反应）
    QColor backgroundColor;
    if(option.state & QStyle::State_Selected){
        backgroundColor = QColor(100, 150, 200); // 选中是深蓝色
    }
    else if(option.state & QStyle::State_MouseOver){
        backgroundColor = QColor(173,216,230);// 鼠标悬浮是蔚蓝色
    }
    else {
        backgroundColor = option.palette.window().color();// 否则是默认的颜色
    }
    painter->setBrush(backgroundColor);// 设置颜色
    painter->setPen(Qt::NoPen);// 不带边框
    painter->drawRect(option.rect);// 绘制背景

    // 3.绘制左边的头像
    QPixmap pixmap = index.data(Qt::UserRole + 1).value<QPixmap>();
    painter->drawPixmap(option.rect.x() + 5,option.rect.y() + 5,40,40, pixmap.scaled(40,40,Qt::KeepAspectRatioByExpanding,Qt::SmoothTransformation));

    // 4.绘制中间上方的名字
    QColor textColor = Qt::black;
    QFont font = painter->font();//默认字体
    font.setPointSize(10);//设置字号
    painter->setFont(font);
    painter->setPen(textColor);
    QString text1 = index.data(Qt::UserRole + 2).toString();
    painter->drawText(option.rect.x() + 50,option.rect.y() + 5,100,16, Qt::AlignVCenter, text1);

    // 5.绘制中间下方的上一次聊天信息
    textColor = Qt::gray;
    painter->setPen(textColor);
    QString text2 = index.data(Qt::UserRole + 5).toString();

    QString truncatedText;// 保存省略后的文本
    QFontMetrics fm(painter->font());
    int textWidth = fm.horizontalAdvance(text2);
    if (textWidth > 140) {
        QString ellipsis = "...";// 预留三个字符的宽度用于“...”
        int ellipsisWidth = fm.horizontalAdvance(ellipsis);
        int availableWidth = 140 - ellipsisWidth;// 剩余的宽度用于显示文本
        // 截取文本，使其适应剩余宽度
        truncatedText = fm.elidedText(text2, Qt::ElideRight, availableWidth);
    }
    else {
        truncatedText = text2;// 文本宽度小于标签宽度，直接显示原文本
    }
    painter->drawText(option.rect.x() + 50,option.rect.y() + 29,140,16, Qt::AlignVCenter, truncatedText);

    // 6.绘制右边的未读消息（如果有的话）
    if(index.data(Qt::UserRole + 3).value<bool>() == true){
        painter->setBrush(Qt::red);// 未读消息显示成红色
        painter->drawEllipse(option.rect.x() + 155,option.rect.y() + 5,16,16);
    }

    painter->restore();// 恢复绘制状态
}

MyTextEdit::MyTextEdit(QWidget *parent):QTextEdit(parent){}

void MyTextEdit::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter){
        // 如果同时按下了Ctrl，则换行
        if(event->modifiers() & Qt::ControlModifier){
            this->insertPlainText("\n");
            return;
        }else{
            emit keyForSendMsg();// 发送信号，触发发送事件
            return;
        }
    }
    QTextEdit::keyPressEvent(event);
}

ChatAvatarLabel::ChatAvatarLabel(QWidget *parent):QLabel(parent){}

void ChatAvatarLabel::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton){
        QString id = this->objectName();
        emit chatAvatarLabelClicked(id);
    }
    QLabel::mousePressEvent(event);
}

PhotoLabel::PhotoLabel(QWidget *parent):QLabel(parent){}

void PhotoLabel::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton){
        QPixmap pix = this->pixmap();
        emit showAPhoto(pix);
    }
    QLabel::mousePressEvent(event);
}
